import {defineStore} from 'pinia';
import router from 'router/index'
import {ref} from 'vue';
import type {RouteData} from './type/type'
import  {Keys as keyName} from './type/type'
import roles from './type/data'
const modules = import.meta.glob('../../views/*/*.vue');
export const userInfoStore=defineStore('userInfoStore',()=>{
    const userName=ref('测试用户')
    const rolesInfo=ref<RouteData[]>([
       {
        path:'',
        paths:'',
        name:'',
        redirect:'',
        meta:'',
        component:()=>{},
        children:[]
       }
    ])
    function getRouterInfo(){
    
       return new Promise((resolve, reject)=>{
          let accessRoutes=getAsyncRoutes(roles.mobile,'');
          rolesInfo.value=accessRoutes
           for (const newItem of accessRoutes) {

              if(newItem.component instanceof Function){
   
                router.addRoute({
                  path:newItem.path,
                  name:newItem.name,
                  redirect:newItem.redirect,
                  component:newItem.component,
                  children:(newItem.children as any)
                })

            
              }

            }
            
            setTimeout(()=>{resolve(accessRoutes)},3000)
       
        })
    }
    return {userName,getRouterInfo,rolesInfo};
})

const keys:string[] = [keyName.PATH, keyName.NAME, keyName.CHILDREN, keyName.REDIRECT,keyName.META]
function getAsyncRoutes(routes:RouteData[],paths:string) {
    const res:RouteData[]=[];
    

    routes.forEach((item:RouteData) => {

      let newItem:RouteData={
        path:'',
        paths:'',
        name:'',
        redirect:'',
        meta:'',
        component:()=>{},
        children:[]
      };
      for (const key in item) {
        if (keys.includes(key)) {
          newItem[key] = item[key];
        }
      }

        if (item.component!='' ) {
            newItem.component = modules[`../../views/${item.component}`]

        }else{
            newItem.component =modules[`../../views/RouterView/index.vue`]
        }

        

        if(paths!=""){

          newItem.paths=paths+"/"+item.path;
        }else{
          newItem.paths=item.path;
        }

        if (item.children && item.children.length) {
          
          newItem.children = getAsyncRoutes(item.children,newItem.paths)
        }

        
        res.push(newItem)

    })

    return res
}


// let accessRoutes=getAsyncRoutes(roles.mobile,'');



//  for (const newItem of accessRoutes) {

//   if(newItem.component instanceof Function){
 
//     router.addRoute({
//       path:newItem.path,
//       name:newItem.name,
//       redirect:newItem.redirect,
//       component:newItem.component,
//       children:(newItem.children as any)
//     })

 
//   }

// }